<template>
  <div>
    <ComHeader title="我的钱包" leftArrow="true"/>
    <div class="container">
      <!-- 个人信息 -->
      <div class="container-bj">
        <div class="userInfo" v-if="userInfo">
          <img :src="userInfo.headimgurl">
          <p class="nickname">{{userInfo.nickname}}</p>
          <p class="level">{{userInfo.level}}</p>
        </div>
      </div>

      <div class="money-main">
        <!-- 提现展示 -->
        <div class="moneys">
          <font @click.stop.prevent="goWithdrawalHistoryFn">已提现</font>：
          <span>{{yiti}} 元</span>&nbsp;&nbsp;&nbsp;
          余额：
          <span>{{money}} 元</span>
        </div>
        <div class="money-input">
          <input
            type="number"
            v-model="moneyNum"
            placeholder="请输入提现金额"
            id="money-number"
            @input="regmoney"
          >
          <!-- <p class="money-tips">ps：提现金额每次不小于 100 元，每天不大于 5000 元</p> -->
        </div>
        <!-- 流水展示 -->
        <div class="money-flow">
          <div class="money-fixed" v-if="record && record.length">
            <scroll
              class="scroll"
              :data="record"
              :pullup="isPullup"
              @scrollToEnd="searchMore"
              ref="suggest"
            >
              <ul>
                <li>
                  <span class="flow-price">金额</span>
                  <span class="flow-state">状态</span>
                  <span class="flow-date">时间</span>
                </li>
                <li v-for="(item, index) in record" :key="index">
                  <span class="flow-price">{{item.agent_tixian_fee}}</span>
                  <span class="flow-state">{{item.state}}</span>
                  <span class="flow-date">{{item.addtime}}</span>
                </li>
                <!--底部loading-->
                <loading v-show="isHasMore" title="加载中..."></loading>
                <p class="not-tit" v-if="record.length && !isHasMore">————我是有底线的————</p>
              </ul>
              <div v-show="!isHasMore && !record.length" class="no-result-wrapper">
                <span>抱歉，暂无记录</span>
              </div>
            </scroll>
          </div>
          <p class="notData" v-else>暂无流水</p>
        </div>
        <div class="money-btn theme-background" @click="clickMoneyBtn()">立即提现</div>
      </div>
    </div>
  </div>
</template>

<script>
import ComHeader from "@/common/ComHeader";
import Scroll from "@/base/scroll/scroll";
import Loading from "@/base/loading/loading";
import api from "@/fetch/api";
import { Toast } from "mint-ui";
import axios from "axios";

export default {
  name: "Mycontainer",
  data() {
    return {
      userInfo: null,
      myBalance: true,
      moneyNum: null,
      record: [],
      userInfo: null,
      moreList: [],
      money: "0.00",
      yiti: "0.00",
      page: 1,
      limit: 10, // 每页显示多少条
      isPullup: true, // 是否需要滚动结束派发事件
      isHasMore: true, // 是否价值底部loading
      nextPage: null // 是否存在下一页
    };
  },
  components: {
    ComHeader,
    Toast,
    Loading,
    Scroll
  },

  created() {
    // 获取缓存的用户信息
    var ethelWxUserInfo = this.getlocalStorage(this.companyUnique);
    this.userInfo = ethelWxUserInfo;
    // 当存在缓存时，获取余额，提现额
    if (ethelWxUserInfo) {
      // 获得手机号码
      const params = {
        uid: this.getUId()
      }; 

      // 获取个人余额，参数username（手机号码）
      api.getMyBalance(params).catch(error => {
        this.money = error.data.data.balance;
        // 当手机号不存在，获取不到个人余额，则显示为0
        if (error.data.msg == "该用户不存在") {
          this.money = 0;
        }
      });

      // 获得已提现金额，参数username（手机号码），当号码不存在时，返回的是 0
      api.gettxCount(params).catch(error => {
        this.yiti = error.data.sum;
      });

      // 当没有缓存wxUserInfo时，使用默认头像（后期可以删除）
    } else {
      this.userInfo = {
        nickname: "塞拉菲娜体验用户",
        headimgurl:
          "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJicOCm5pTDEhtk4TLA3EszTOzbUDNTicCgcIgs0080ciaXEQrp2Vdib3DrnpRUPDwbrqoNmVP3iaqwoeg/132",
        level: "普通会员"
      };
    }
  },
  mounted() {
    this.getRecord(); // 获得流水列表
  },
  methods: {
    regmoney() {
      if (this.moneyNum.toString().indexOf(".") > 0) {
        if (this.moneyNum.toString().split(".")[1].length > 2) {
          Toast("保留至小数点后两位");
          this.moneyNum = Number(this.moneyNum).toFixed(2);
        }
      }
    },
    // 下拉加载
    searchMore() {
      if (this.nextPage) {
        this.page++;
        this.getRecord(true);
      }
    },
    // 获取流水，参数username（手机号码），type（类型）
    getRecord(isLoading = false) {
      const params = {
        username: this.getUserId(),
        type: "tx",
        page: this.page,
        limit: this.limit,
        uid: this.getUId()
      };
      api.getMyRecordList(params).catch(error => {
        this.print(error);
        if (error.status === 200) {
          this.isHasMore = false;
          if (!isLoading && this.$refs.suggest) {
            this.$refs.suggest.scrollTo(0, 0);
          }
          this.record = !isLoading
            ? error.data.results
            : [...this.record, ...error.data.results];
          this.isHasMore = error.data.next ? true : false;
          this.nextPage = error.data.next;
        }
      });
    },

    // 跳转到提现记录
    goWithdrawalHistoryFn() {
      this.$router.push({
        path: "/withdrawalHistory"
      });
    },

    // 立即提现按钮
    clickMoneyBtn() {

      if(window.localStorage.getItem(this.companyUnique)) {
        let ethelWxUserInfo = JSON.parse(window.localStorage.getItem(this.companyUnique))
      }
      if (!this.moneyNum) {
        Toast("请输入提现金额");
      }  else {
        // 提现请求，参数username（手机号码），提现金额（数字）
        const params = {
          uid: this.getUId(),
          money: this.moneyNum
        };
        api.getMyRecord(params).catch(res => {
          // 本地存储余额，减去提现的金额，重新写入本地存储余额！！！！！！！！！！！！！！
          // 提现请求成功 
          // 请求成功，余额充足
          if (res.data.msg == "已提现，正在审核") {
            Toast("成功提现 " + this.moneyNum + " 元");

            // 刷新本地余额
            const params1 = {
              uid: this.getUId()
            };
            api.getMyBalance(params1).catch(error => {
              this.moneyNum = "";
              const params = {
                uid: this.getUId()
              };
              api.getMyBalance(params).catch(error => {
                this.money =  error.data.data.balance;
                this.getRecord()
                // 当手机号不存在，获取不到个人余额，则显示为0
                if (error.data.msg == "该用户不存在") {
                  this.money = 0;
                }
              });
            });
            // 请求成功，余额不足
          } else {
            Toast(res.data.msg);
           
            
          }
          this.moneyNum = "";
        });
      }
    },

    // 控制上一页
    clickPrevMore(url) {
      axios.get(url).catch(res => {
        this.print(res);
        this.record = res.data;
      });
    },

    // 控制下一页
    clickNextMore(url) {
      axios.get(url).catch(res => {
        this.print(res);
        this.record = res.data;
      });
    }
  }
};
</script>

<style lang="stylus" scoped>
.container {
  width: 100%;
  height: 5rem;
  position: absolute;
  top: 1.45rem;

  .container-bj {
    width: 100%;
    height: 100%;
    background: url('/static/img/bj2.png') no-repeat;
    background-size: 100% 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    img {
      width: 2.3rem;
      height: 2.3rem;
      border-radius: 50%;
    }

    p {
      font-size: 0.35rem;
      color: #ffffff;
    }

    // 用户信息
    .userInfo {
      text-align: center;

      .nickname {
        font-size: 0.46rem;
        padding: 0.2rem 0;
      }

      .level {
        font-size: 0.4rem;
      }
    }
  }
}

.no-result-wrapper {
  position: absolute;
  width: 100%;
  top: 50%;
  text-align: center;
  color: #666;
  font-size: 0.35rem;
  transform: translateY(-50%);
}

.money-fixed {
  position: absolute;
  width: 100%;
  bottom: 0;
  top: 0;
}

.scroll {
  height: 100%;
  overflow: hidden;
}

.not-tit {
  width: 100%;
  height: 30px;
  line-height: 30px;
  text-align: center;
  color: #666;
  font-size: 0.35rem;
}

.money-main {
  height: 100%;
  padding-bottom: 1.6rem;

  .moneys {
    text-align: center;
    padding: 0.4rem 0;
    font-size: 0.45rem;

    span {
      color: #ff555f;
    }
  }

  .moneys>font {
    color: #26a2ff;
    text-decoration: underline;
  }

  .money-input {
    width: 90%;
    margin: 0 auto;

    .money-tips {
      color: #ff555f;
      padding: 0.1rem 0;
    }
  }

  .money-input input {
    border: 1px solid #ddd;
    padding: 0.3rem;
    width: 100%;
    border-radius: 0.2rem;
  }

  .money-btn {
    width: 90%;
    margin: 0 auto;
    border-radius: 0.15rem;
    line-height: 1.2rem;
    text-align: center;
    margin-top: 0.8rem;
  }
}

.money-flow {
  width: 90%;
  margin: 0.5rem auto;
  border: 1px solid #ddd;
  position: relative;
  background: #fff;
  height: 4.6rem;
  overflow: auto;
  margin-top: 0px;

  ul {
    height: auto;
    text-align: center;

    li {
      padding-bottom: 0.2rem;
      padding-top: 0.15rem;
      border-bottom: 1px dotted #ddd;
    }

    span {
      display: inline-block;
      color: #777;
    }

    .flow-price {
      width: 18%;
    }

    .flow-state {
      width: 28%;
      font-size: 0.35rem;
    }

    .flow-date {
      width: 50%;
      color: #999;
    }
  }
}

.myScroller {
  position: absolute;
  bottom: 0.3rem;
  width: 88%;
  left: 50%;
  margin-left: -44%;
  text-align: left;
  font-size: 0.3rem;
  color: #777;

  .prev {
    float: left;
  }

  .next {
    float: right;
  }
}
</style>
